<template>
  <div>
    <!-- 三方票号查询 -->
    <TopFilter :list="topFilterList" :cols="3" @filterChange="changeHandle" @resetChange="resetChange" @onCollapse="collapseHandle" :labelWidth="110"></TopFilter>

    <Spin :spinning="exportLoading" tip="Loading...">
      <FilterTables
        ref="table"
        columnsRef="qjhInvoiceNumberQuery"
        :isSelectColumn="false"
        :columns="columns"
        :fetchapi="fetchApi"
        :params="fetchParams"
        :datakey="'records'"
        :rowstyles="rowstyles"
        :onSyncTableData="syncTableData"
        :onColumnsChange="(columns) => (this.columns = columns)"
      >
        <template slot="controls">
          <multiuse-button size="small" type="primary" :click="exportHandle">导 出</multiuse-button>
        </template>
      </FilterTables>
    </Spin>

    <BaseDialog
      :visible.sync="visible"
      :title="detialType === 'realAmount' ? '已用金额明细' : '预扣金额明细'"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <SonModel :rowData="formData" :type="detialType" @close="emitCloseHandler1" />
    </BaseDialog>
    <!-- 经销商查询 -->
    <BaseDialog :visible.sync="isDealer" title="经销商查询" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <OwnerSearch :rowData="formData" @close="emitCloseHandler" />
    </BaseDialog>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { getLevelOneArea } from '@/api/cms-common/dealerdata/index';
import { region } from '@/api/cms-common/region'; //行政区域
import { queryList, exportExcel, gettmFiAccountType, exporturl } from '@/api/omFinanceP/FinanceManage/InvoiceNumberQuery';
import { exportExcelFile } from '@/utils/index';
import OwnerSearch from './OwnerSearch';
import SonModel from './SonModel';

export default {
  name: 'InvoiceNumberQuery',
  mixins: [dictionary, region],

  data() {
    this.BaseTable = null;
    return {
      ORG_TYPE_MARKETING_WAR_AREA: 15061015, // 营销战区
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      fetchApi: queryList,
      fetchParams: {
        xhrAbort: false,
      },
      formData: {},
      rowstyles: [],
      visible: false,
      isDealer: false,
      exportLoading: false,
      dealerCodes: '',
      detialType: null,
    };
  },
  components: {
    OwnerSearch,
    SonModel,
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.getTopLevelArea(this.ORG_TYPE_MARKETING_WAR_AREA, 'areaId');
    this.initProvince();
  },
  created() {
    this.gettmFiAccountType();
  },
  methods: {
    // 所属区域
    async getTopLevelArea(areaType, filedName) {
      const res = await getLevelOneArea(areaType);
      if (res.resultCode === 200) {
        this.topFilterList.find((item) => item.fieldName === filedName).itemList = res.data.map((x) => ({ value: parseInt(x.id), text: x.orgName }));
      }
    },

    //初始化所在省份
    async initProvince() {
      let pl = await this.createRegionList();
      this.topFilterList.find((item) => item.fieldName === 'provinceId').itemList = pl;
    },
    //初始化所在市数据
    async initCity(provinceId) {
      this.topFilterList.find((item) => item.fieldName == 'cityId').initialValue = '';
      this.topFilterList.find((item) => item.fieldName == 'cityId').itemList = [];
      if (!provinceId || provinceId == null || typeof provinceId == 'undefined') {
        return;
      }
      //取省数据
      let rd = this.getRegionData();
      this.cityData = rd[provinceId].children;
      let cl = this.createSubRegionList(this.cityData);
      //初始化市，清除原值
      let city = this.topFilterList.find((item) => item.fieldName === 'cityId');
      city.itemList = cl;
      city.initialValue = '';
    },

    detailHandle(row, type) {
      this.visible = true;
      this.detialType = type;
      this.formData = row;
    },
    emitCloseHandler1(val) {
      this.visible = val;
    },
    seacherFun() {
      this.isDealer = true;
    },
    emitCloseHandler(val, data) {
      this.isDealer = val;
      if (data) {
        let dealerCodes = [];
        let dealerNames = [];
        data.map((x) => {
          dealerCodes.push(x.dealerCode);
          dealerNames.push(x.dealerName);
        });
        this.topFilterList.find((x) => x.fieldName == 'ownerCode').initialValue = dealerCodes.toString();
      }
    },
    changeHandle(params) {
      this.fetchParams.xhrAbort = false;
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    resetChange(params) {
      this.dealerCodes = '';
      this.fetchParams.xhrAbort = false;
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    syncTableData(data) {
      if (!data.length) return;
      data.forEach((x) => {
        if (x.isDeleted == 1) {
          this.rowstyles.push({ row: x, styles: { backgroundColor: '#909399' } });
        }
      });
    },
    // 资金类型
    async gettmFiAccountType() {
      const res = (await gettmFiAccountType({ fundsType: 0 })).data.map((x) => ({ text: x.accountTypeName, value: x.id }));
      this.topFilterList.find((x) => x.fieldName == 'accountType').itemList = res;
    },
    // 导出
    async exportHandle() {
      // let json = Object.assign({}, { CODE: 'CODE_0000091' }, this.fetchParams);
      // let res = await exporturl(json);
      // if (res.resultCode == 200) {
      //   this.$router.push('/admin/auth/oem/downloadCenter');
      // }
      await this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
        confirmButtonText: '下载',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.exportLoading = true;

          exportExcel(this.fetchParams)
            .then((response) => {
              exportExcelFile(response.data, '三方票号查询');
              this.exportLoading = false;
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消',
          });
        });
    },

    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    createdFrom() {
      return [
        {
          type: 'SELECT',
          label: '所属区域',
          fieldName: 'areaId',
          placeholder: '请选择',
          itemList: [],
        },
        { type: 'SELECT', label: '省份', fieldName: 'provinceId', placeholder: '请选择', initialValue: '', itemList: [], change: (props) => this.initCity(props) },
        { type: 'SELECT', label: '城市', fieldName: 'cityId', placeholder: '请选择', initialValue: '', itemList: [] },
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'ownerCode',
          placeholder: '输入多个经销商代码时，请用英文逗号隔开',
          // unitRender: () => {
          //   return (
          //     <div>
          //       <el-button icon="el-icon-search" onClick={() => this.seacherFun()}></el-button>
          //     </div>
          //   );
          // }
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入',
        },
        {
          type: 'INPUT',
          label: '三方票号',
          fieldName: 'billNo',
          placeholder: '请输入',
        },
        {
          type: 'SELECT',
          label: '资金类型',
          fieldName: 'accountType',
          placeholder: '请选择',
          itemList: [],
        },
        {
          type: 'RANGE_DATE',
          label: '记账时间范围',
          fieldName: 'startAccountDate|endAccountDate',
          dateType: 'exactdaterange',
          placeholder: '请选择',
        },
        {
          type: 'RANGE_DATE',
          label: '到期日期',
          fieldName: 'startExpireDate|endExpireDate',
          dateType: 'exactdaterange',
          placeholder: '请选择',
        },
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '所属区域',
          dataIndex: 'areaName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '省份',
          dataIndex: 'provinceName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '城市',
          dataIndex: 'cityName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '经销商代码',
          dataIndex: 'ownerCode',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '经销商名称',
          dataIndex: 'dealerName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '资金类型',
          dataIndex: 'accountTypeName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '记账时间',
          dataIndex: 'accountDate',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '三方票号',
          dataIndex: 'billNo',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '票面金额',
          dataIndex: 'billAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          align: 'right',
          precision: 2,
          numberFormat: true,
        },
        {
          title: '可用余额',
          dataIndex: 'availableAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          align: 'right',
          precision: 2,
          numberFormat: true,
        },
        {
          title: '预扣金额',
          dataIndex: 'frozenAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          align: 'right',
          precision: 2,
          numberFormat: true,
          render: (props) => {
            return (
              <el-link type="warning" underline={true} onClick={() => this.detailHandle(props.row, 'frozenAmount')}>
                {props.row.frozenAmount ? props.row.frozenAmount.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',') : ''}
              </el-link>
            );
          },
        },
        {
          title: '已用金额',
          dataIndex: 'realAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          align: 'right',
          precision: 2,
          numberFormat: true,
          render: (props) => {
            return (
              <el-link type="warning" underline={true} onClick={() => this.detailHandle(props.row, 'realAmount')}>
                {props.row.realAmount ? props.row.realAmount.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',') : ''}
              </el-link>
            );
          },
        },
        {
          title: '出票日期',
          dataIndex: 'billDate',
          sorter: true,
          filter: true,
          filterType: 'date-range',
        },
        {
          title: '到期日期',
          dataIndex: 'expireDate',
          sorter: true,
          filter: true,
          filterType: 'date-range',
        },
      ];
    },
  },
};
</script>
